﻿//Description:定制化公共js
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2021-11-25
//Rewriter:
//Rewrite Date:

$(function () {
    $(".l-btn").not(".not-custom").addClass('l-btn-custom'); //按钮，统一增加定制化样式
});

/*
Description:easyui-分页定制化
Date:2021-11-25
Writer:Wangjh
*/
function customizedEasyuiPagination(id) {
    var p = $("#" + id);
    p.find('table tbody tr td a .l-btn-left .l-btn-text:eq(0)').html('首页 |');
    p.find('table tbody tr td a .l-btn-left .l-btn-text:eq(1)').html('上一页 |');
    p.find('table tbody tr td a .l-btn-left .l-btn-text:eq(2)').html('下一页 |');
    p.find('table tbody tr td a .l-btn-left .l-btn-text:eq(3)').html('尾页 |');
    p.find(".l-btn-icon").text('');
}
/*
Description:easyui-分页定制化,包含自定义行数
Date:2023-1-1
Writer:Longbin
*/
function NewcustomizedEasyuiPagination(id) {
    var p = $("#" + id);
    if (!p.find('table tbody tr td input').hasClass("pageSize")) {
        p.find('table tbody tr td .l-btn:eq(0)').before('<input class="pageSize"  style="width:40px;height:22px;border: 1px solid #ddd;text-align:center;"/>');
    }
    p.find('table tbody tr td a .l-btn-left .l-btn-text:eq(0)').html(' | 首页 |');
    p.find('table tbody tr td a .l-btn-left .l-btn-text:eq(1)').html('上一页 |');
    p.find('table tbody tr td a .l-btn-left .l-btn-text:eq(2)').html('下一页 |');
    p.find('table tbody tr td a .l-btn-left .l-btn-text:eq(3)').html('尾页 |');
    p.find(".l-btn-icon").text('');
}

/*
Description:linkbutton禁止和释放bug修复
Date:2021-11-25
Writer:Wangjh
*/
if ($.fn.linkbutton != null && $.fn.linkbutton.methods != null) {
    $.extend($.fn.linkbutton.methods, {
        /**
        * 激活选项（覆盖重写）
        * @param {Object} jq
        */
        enable: function (jq) {
            return jq.each(function () {
                var state = $.data(this, 'linkbutton');
                if ($(this).hasClass('l-btn-disabled')) {
                    var itemData = state._eventsStore;
                    //恢复超链接
                    if (itemData.href) {
                        $(this).attr("href", itemData.href);
                    }
                    //回复点击事件
                    if (itemData.onclicks) {
                        for (var j = 0; j < itemData.onclicks.length; j++) {
                            $(this).bind('click', itemData.onclicks[j]);
                        }
                    }
                    //设置target为null，清空存储的事件处理程序
                    itemData.target = null;
                    itemData.onclicks = [];
                    $(this).removeClass('l-btn-disabled');
                }
            });
        },
        /**
        * 禁用选项（覆盖重写）
        * @param {Object} jq
        */
        disable: function (jq) {
            return jq.each(function () {
                var state = $.data(this, 'linkbutton');
                if (!state._eventsStore)
                    state._eventsStore = {};
                //if (!$(this).hasClass('l-btn-disabled')) {
                var eventsStore = {};
                eventsStore.target = this;
                eventsStore.onclicks = [];
                //处理超链接
                var strHref = $(this).attr("href");
                if (strHref) {
                    eventsStore.href = strHref;
                    $(this).attr("href", "javascript:void(0)");
                }
                //处理直接耦合绑定到onclick属性上的事件
                var onclickStr = $(this).attr("onclick");
                if (onclickStr && onclickStr != "") {
                    eventsStore.onclicks[eventsStore.onclicks.length] = new Function(onclickStr);
                    $(this).attr("onclick", "");
                }
                //处理使用jquery绑定的事件
                var eventDatas = $(this).data("events") || $._data(this, 'events');
                if (eventDatas["click"]) {
                    var eventData = eventDatas["click"];
                    for (var i = 0; i < eventData.length; i++) {
                        if (eventData[i].namespace != "menu") {
                            eventsStore.onclicks[eventsStore.onclicks.length] = eventData[i]["handler"];
                            $(this).unbind('click', eventData[i]["handler"]);
                            i--;
                        }
                    }
                }
                state._eventsStore = eventsStore;
                $(this).addClass('l-btn-disabled');
                //}
            });
        }
    });
}

/*
Description:获取网站路径
Date:2021-11-25
Writer:Wangjh
*/
function getRootPath() {
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht = curWwwPath.substring(0, pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    return (localhostPaht + projectName);
}
/*
Description:获取网站IP
Date:2021-11-25
Writer:Wangjh
*/
function getIp() {
    var curWwwPath = window.document.location.href;
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht = curWwwPath.substring(0, pos);
    return localhostPaht;
}

/*
Description:判断字符串是否全部由空格或换行符组成
Date:2021-11-25
Writer:Wangjh
*/
function isNullOrWhiteSpaceStr(data) {
    var reg = /^\s*$/;
    //返回值为true表示是空字符串
    return !(data != null && data != undefined && !reg.test(data));
}
/*
Description:提示消息(两种方式)
Date:2021-11-25
Writer:Wangjh
*/
function displayMessage(message, isTrue, isPop) {

    if (document.getElementById("statusMessage") && isPop != true) {
        if (isTrue) {
            document.getElementById("statusMessage").style.color = "#000000";
        }
        else {
            document.getElementById("statusMessage").style.color = "#FF0000";
        }
        document.getElementById("statusMessage").innerText = "消息:" + message;
        return;
    }

    if (isTrue) {
        $.messager.show({
            title: '',
            width: '800',
            height: '50',
            msg: message,
            timeout: 1000,
            showType: 'slide',
            style: {
        }
    });
} else {
    $.messager.alert('错误', message, 'error');
}

}
/*
Description:提示消息清除
Date:2021-11-25
Writer:Wangjh
*/
function clearMessage() {
    if (document.getElementById("statusMessage")) {
        document.getElementById("statusMessage").innerText = "";
    }
}

/*
Description:提示消息(两种方式),并释放按钮
Date:2021-11-25
Writer:Wangjh
*/
function displayMessage2(message, isTrue, releaseBtnIds) {
    displayMessage(message, isTrue);
    for (var i = 0; i < releaseBtnIds.length; i++) {
        if ($("#" + releaseBtnIds[i]).hasClass('easyui-linkbutton')) {
            $("#" + releaseBtnIds[i]).linkbutton('enable');
        } else {
            $("#" + releaseBtnIds[i]).removeAttr("disabled");
        }
    }
}

/*
Description:url传参获取
Date:2021-11-25
Writer:Wangjh
*/
function getParam(name) {
    try {
        var url = window.document.location.href;
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = url.split('?')[1].match(reg);
        if (r != null) {
            return r[2];
        }
        return ""; //如果此处只写return;则返回的是undefined
    } catch (e) {
        return ""; //如果此处只写return;则返回的是undefined
    }
}
/*
Description:判断文件是否存在
Date:2021-11-25
Writer:Wangjh
*/
function isExistFile(url) {
    var result = false;
    jQuery.support.cors = true;
    $.ajax({
        type: "Get",
        url: url,
        cashe: false,
        async: false,
        xhrFields: { withCredentials: true },         //跨域带cookie
        crossDomain: true,
        beforeSend: function () {

        },
        success: function (data) {
            result = true;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert(XMLHttpRequest.responseText);
        }

    });
    return result;
}
/*
Description:easyui datagrid数据清除
Date:2021-12-20
Writer:Wangjh
*/
function clearEasyuiDataGrid(id, type) {
    if (type == null) {
        $("#" + id).datagrid('loadData', { total: 0, rows: [] });
        return;
    }

    if (type == 1) //此种方式在IE8下快点
    {
        var item = $('#' + id).datagrid('getRows');
        if (item) {
            for (var i = item.length - 1; i >= 0; i--) {
                var index = $('#' + id).datagrid('getRowIndex', item[i]);
                $('#' + id).datagrid('deleteRow', index);
            }
        }
    }
}

/*
Description:数字自动补齐前面为c
Date:2021-12-20
Writer:Wangjh
*/
function padStart(num, n, c) {
    return (Array(n).join(c) + num).slice(-n);
}

/*
Description:easyui-日期按钮增加清除
Date:2022-01-18
Writer:Wangjh
*/
function addClearBtnToDatebox() {
    var dateboxBtn = $.extend([], $.fn.datebox.defaults.buttons);
    dateboxBtn.splice(1, 0, {
        text: '清除',
        handler: function (target) {
            $(target).datebox("setValue", "");
        }
    });
    //统一给日期控件增加清除按钮
    $('.easyui-datebox').datebox({
        buttons: dateboxBtn
    });
}
/*
Description:格式化后台返回的日期字符串yyyy-mm-dd，只剩日期
Date:2022-01-18
Writer:Wangjh
*/
function formatDate(strDate) {
    return strDate.replace("T", "").replace("00:00:00", "").replace("0:00:00", "").replace(/\//g, "-").replace(" ", "");
}
/*
Description:设置cookie
Date:2022-02-19
Writer:Wangjh
*/
function setCookie(name, value, overdueMinutes, path) {
    // 对 cookie 值进行编码以转义其中的分号、逗号和空格
    var cookie = name
    if (value == null || value == "") {
        cookie += "=''";
    } else {
        cookie += "=" + encodeURIComponent(value);
    }

    //过期分钟
    if (typeof overdueMinutes === "number") {
        /* 设置 max-age 属性 */
        cookie += "; max-age=" + (overdueMinutes * 60);
    }
    if (path == null || path == "") {
        cookie += ";path=/";
    } else {
        cookie += ";path=" + path;
    }
    document.cookie = cookie;
}
/*
Description:获取cookie
Date:2022-02-19
Writer:Wangjh
*/
function getCookie(name) {
    // 拆分 cookie 字符串
    var cookieArr = document.cookie.split(";");
    // 循环遍历数组元素
    if (cookieArr == "" || cookieArr == null) {
        return null;
    }
    for (var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");

        /* 删除 cookie 名称开头的空白并将其与给定字符串进行比较 */
        if (name == cookiePair[0].replace(/(^\s*)|(\s*$)/g, "")) {
            // 解码cookie值并返回
            return decodeURIComponent(cookiePair[1]);
        }

    }
    // 如果未找到，则返回null
    return null;
}
/*
Description:清除cookie
Date:2022-02-19
Writer:Wangjh
*/
function clearCookie(name, path) {
    setCookie(name, "", -1 * 24 * 60, path);

}
/*
Description:数组合并去重
Date:2022-03-02
Writer:Wangjh
*/
function mergerNoRepeat(arr1, arr2) {
    var flag;
    for (var i = 0; i < arr2.length; i++) {
        flag = false;
        for (var j = 0; j < arr1.length; j++) {
            if (JSON.stringify(arr1[i]) == JSON.stringify(arr2[j])) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            arr1.push(arr2[i]);
        }
    }
}

//文件下载（url:后台请求地址，param：请求参数） add by zhangrj 20231018
function FileDownLoad(url, param) {
    //判断是否ie浏览器
    if (window.ActiveXObject || "ActiveXObject" in window) {
        displayMessage("请用谷歌浏览器进行导出操作", false);
        return;
    }
    $.messager.progress({ text: '', msg: '处理中...' });
    var xhr = new XMLHttpRequest(); //定义一个XMLHttpRequest对象
    xhr.open("post", url, true);
    xhr.responseType = 'blob'; //设置ajax的响应类型为blob
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
    xhr.onload = function ()//当请求完成，响应就绪进入
    {
        if (this.status === 200)//当响应状态码为200时进入
        {
            if (xhr.getResponseHeader("fileDownload") == "1") {
                var blob = this.response; //获取响应返回的blob对象
                var a = document.createElement('a'); //在dom树上创建一个a标签
                var fileurl = window.URL.createObjectURL(new Blob([blob]));
                a.href = fileurl; //将url赋值给a标签的href属性
                a.download = decodeURI(xhr.getResponseHeader("Content-Disposition").split('filename=')[1]);
                a.click(); //主动触发a标签点击事件
            } else {
                var reader = new FileReader();
                reader.readAsText(this.response, 'utf-8');
                reader.onload = function (e) {
                    var result = JSON.parse(reader.result);
                    displayMessage(result.Message, result.Result);
                }
            }
        }
        $.messager.progress('close');
    };
    //判断参数类型
    switch (typeof param) {
        case "object":
            xhr.send($.param(param)); //附带参数发送请求
            break;
        case "undefined":
            xhr.send();
            break;
        default:
            xhr.send(param); //附带参数发送请求
            break;
    }
}



/*----以下是对js标准对象如string增加或修改属性----*/
/*
Description:去除字符串两端的字符
Date:2022-02-21
Writer:Wangjh
*/
String.prototype.trim = function (c) {
    if (c == null || c == "") {
        var reg = /(^\s+)|(\s+$)/g
        var str = this.replace(reg, "")
        return str;
    }
    else {
        var rg = new RegExp("^" + c + "*");
        var str = this.replace(rg, '');
        rg = new RegExp(c);
        var i = str.length;
        while (rg.test(str.charAt(--i)));
        return str.slice(0, i + 1);
    }
}
/*
Description:去除字符串前面的字符
Date:2022-02-21
Writer:Wangjh
*/
String.prototype.trimStart = function (c) {
    if (c == null || c == "") {
        var str = this.replace(/^\s*/, '');
        return str;
    }
    else {
        var rg = new RegExp("^" + c + "*");
        var str = this.replace(rg, '');
        return str;
    }
}

/*
Description:去除字符串后面的字符
Date:2022-02-21
Writer:Wangjh
*/
String.prototype.trimEnd = function (c) {
    if (c == null || c == "") {
        var reg = /\s+$/g
        var str = this.replace(reg, "")
        return str;
    }
    else {
        var str = this;
        var rg = new RegExp(c);
        var i = str.length;
        while (rg.test(str.charAt(--i)));
        return str.slice(0, i + 1);
    }
}


/*
Description:操作日志统一弹窗
Date:2023-12-21
Writer:zhangrj
*/
$.fn.operaLogDialog = function (param) {
    var obj = $(this);
    if (param === undefined) {
        obj.html('<div class="dvgrid-cellwarp" style="background: #fff; margin: 3px 0px 3px 3px"><table id="operaLogTable" class="easyui-datagrid" data-options="rownumbers:true,fitColumns:true"></table></div>');
        //操作内容列表
        $("#operaLogTable").datagrid({
            columns: [[
                 { field: 'FULLNAME', title: '操作人', width: 100 },
                 { field: 'OPERATIONDATE', title: '操作时间', width: 150,
                     formatter: function (value, row, index) {
                         return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
                     }
                 },
                 { field: 'NOTES', title: '修改内容', width: 350 }
	           ]]
        });
        return;
    }

    param = $.extend({ action: "GetCommonMethodOperaLog" }, param);

    $.ajax({
        type: "Post",
        url: getRootPath() + "/Ashx/CommonHandler.ashx",
        data: param,
        cashe: false,
        async: true,
        dataType: "json",
        beforeSend: function () {
            $.messager.progress({ text: '', msg: '处理中...' });
        },
        success: function (res) {
            $.messager.progress('close');
            if (res.Result) {
                obj.dialog({
                    title: '操作日志',
                    top: 50,
                    width: '700px',
                    height: '500px',
                    closed: false,
                    cache: false,
                    modal: true,
                    buttons: [{
                        text: '关闭',
                        handler: function () { obj.dialog('close'); }
                    }]
                });
                $("#operaLogTable").datagrid('loadData', res.DBTable);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.messager.progress('close');
            displayMessage(XMLHttpRequest.responseText, false);
        }
    });
}